const fs = require('fs').promises;
const path = require('path');
const vscode = require('vscode');

/**
 * 存储常量
 */
const StorageConstants = {
    FOLDERS: {
        TASKS: 'tasks',
    },
    FILES: {
        API_CONVERSATION_HISTORY: 'api_conversation_history.json',
        UI_MESSAGES: 'ui_messages.json',
        CONTEXT_HISTORY: 'context_history.json',
        TASK_METADATA: 'task_metadata.json',
    },
    STATE_KEYS: {
        TASK_HISTORY: 'taskHistory',
        CUSTOM_INSTRUCTIONS: 'customInstructions',
        AUTO_APPROVAL_SETTINGS: 'autoApprovalSettings',
        CHAT_SETTINGS: 'chatSettings',
    }
};

/**
 * 存储管理器类 - 用于管理聊天历史、消息和状态
 */
class StorageManager {
    constructor(context) {
        this.context = context;
        this.globalStoragePath = context.globalStorageUri.fsPath;
    }

    /**
     * 确保任务目录存在
     * @param {string} taskId - 任务ID
     * @returns {Promise<string>} - 目录路径
     */
    async ensureTaskDirectoryExists(taskId) {
        const taskDir = path.join(this.globalStoragePath, StorageConstants.FOLDERS.TASKS, taskId);
        await fs.mkdir(taskDir, { recursive: true });
        return taskDir;
    }

    /**
     * 保存API对话历史
     * @param {string} taskId - 任务ID
     * @param {Array} apiConversationHistory - API对话历史
     */
    async saveApiConversationHistory(taskId, apiConversationHistory) {
        try {
            const taskDir = await this.ensureTaskDirectoryExists(taskId);
            const filePath = path.join(taskDir, StorageConstants.FILES.API_CONVERSATION_HISTORY);
            await fs.writeFile(filePath, JSON.stringify(apiConversationHistory, null, 2));
        } catch (error) {
            console.error('保存API对话历史失败:', error);
        }
    }

    /**
     * 获取保存的API对话历史
     * @param {string} taskId - 任务ID
     * @returns {Promise<Array>} - API对话历史
     */
    async getSavedApiConversationHistory(taskId) {
        try {
            const taskDir = await this.ensureTaskDirectoryExists(taskId);
            const filePath = path.join(taskDir, StorageConstants.FILES.API_CONVERSATION_HISTORY);
            try {
                const data = await fs.readFile(filePath, 'utf8');
                return JSON.parse(data);
            } catch (error) {
                if (error.code === 'ENOENT') {
                    return []; // 文件不存在，返回空数组
                }
                throw error;
            }
        } catch (error) {
            console.error('获取API对话历史失败:', error);
            return [];
        }
    }

    /**
     * 保存UI消息
     * @param {string} taskId - 任务ID
     * @param {Array} uiMessages - UI消息
     */
    async saveUiMessages(taskId, uiMessages) {
        try {
            const taskDir = await this.ensureTaskDirectoryExists(taskId);
            const filePath = path.join(taskDir, StorageConstants.FILES.UI_MESSAGES);
            await fs.writeFile(filePath, JSON.stringify(uiMessages, null, 2));
        } catch (error) {
            console.error('保存UI消息失败:', error);
        }
    }

    /**
     * 获取保存的UI消息
     * @param {string} taskId - 任务ID
     * @returns {Promise<Array>} - UI消息
     */
    async getSavedUiMessages(taskId) {
        try {
            const taskDir = await this.ensureTaskDirectoryExists(taskId);
            const filePath = path.join(taskDir, StorageConstants.FILES.UI_MESSAGES);
            try {
                const data = await fs.readFile(filePath, 'utf8');
                return JSON.parse(data);
            } catch (error) {
                if (error.code === 'ENOENT') {
                    return []; // 文件不存在，返回空数组
                }
                throw error;
            }
        } catch (error) {
            console.error('获取UI消息失败:', error);
            return [];
        }
    }

    /**
     * 保存上下文历史
     * @param {string} taskId - 任务ID
     * @param {Object} contextHistory - 上下文历史
     */
    async saveContextHistory(taskId, contextHistory) {
        try {
            const taskDir = await this.ensureTaskDirectoryExists(taskId);
            const filePath = path.join(taskDir, StorageConstants.FILES.CONTEXT_HISTORY);
            await fs.writeFile(filePath, JSON.stringify(contextHistory, null, 2));
        } catch (error) {
            console.error('保存上下文历史失败:', error);
        }
    }

    /**
     * 获取保存的上下文历史
     * @param {string} taskId - 任务ID
     * @returns {Promise<Object>} - 上下文历史
     */
    async getSavedContextHistory(taskId) {
        try {
            const taskDir = await this.ensureTaskDirectoryExists(taskId);
            const filePath = path.join(taskDir, StorageConstants.FILES.CONTEXT_HISTORY);
            try {
                const data = await fs.readFile(filePath, 'utf8');
                return JSON.parse(data);
            } catch (error) {
                if (error.code === 'ENOENT') {
                    return {}; // 文件不存在，返回空对象
                }
                throw error;
            }
        } catch (error) {
            console.error('获取上下文历史失败:', error);
            return {};
        }
    }

    /**
     * 保存任务元数据
     * @param {string} taskId - 任务ID
     * @param {Object} metadata - 元数据
     */
    async saveTaskMetadata(taskId, metadata) {
        try {
            const taskDir = await this.ensureTaskDirectoryExists(taskId);
            const filePath = path.join(taskDir, StorageConstants.FILES.TASK_METADATA);
            await fs.writeFile(filePath, JSON.stringify(metadata, null, 2));
        } catch (error) {
            console.error('保存任务元数据失败:', error);
        }
    }

    /**
     * 获取任务元数据
     * @param {string} taskId - 任务ID
     * @returns {Promise<Object>} - 任务元数据
     */
    async getTaskMetadata(taskId) {
        try {
            const taskDir = await this.ensureTaskDirectoryExists(taskId);
            const filePath = path.join(taskDir, StorageConstants.FILES.TASK_METADATA);
            try {
                const data = await fs.readFile(filePath, 'utf8');
                return JSON.parse(data);
            } catch (error) {
                if (error.code === 'ENOENT') {
                    return { files_in_context: [], model_usage: [] }; // 文件不存在，返回默认元数据
                }
                throw error;
            }
        } catch (error) {
            console.error('获取任务元数据失败:', error);
            return { files_in_context: [], model_usage: [] };
        }
    }

    /**
     * 更新任务历史
     * @param {Object} historyItem - 历史项
     * @returns {Promise<Array>} - 更新后的任务历史
     */
    async updateTaskHistory(historyItem) {
        try {
            // 获取当前任务历史
            const currentTaskHistory = await this.getTaskHistory();
            
            // 查找是否已存在相同ID的任务
            const existingIndex = currentTaskHistory.findIndex(item => item.id === historyItem.id);
            
            if (existingIndex !== -1) {
                // 更新现有任务
                currentTaskHistory[existingIndex] = {
                    ...currentTaskHistory[existingIndex],
                    ...historyItem,
                    ts: Date.now() // 更新时间戳
                };
            } else {
                // 添加新任务
                currentTaskHistory.push({
                    ...historyItem,
                    ts: Date.now()
                });
            }
            
            // 按时间戳排序（最新的在前面）
            currentTaskHistory.sort((a, b) => b.ts - a.ts);
            
            // 保存到扩展全局状态
            await this.context.globalState.update(
                StorageConstants.STATE_KEYS.TASK_HISTORY,
                currentTaskHistory
            );
            
            return currentTaskHistory;
        } catch (error) {
            console.error('更新任务历史失败:', error);
            return [];
        }
    }

    /**
     * 获取任务历史
     * @returns {Promise<Array>} - 任务历史
     */
    async getTaskHistory() {
        const taskHistory = this.context.globalState.get(StorageConstants.STATE_KEYS.TASK_HISTORY);
        return taskHistory || [];
    }

    /**
     * 删除任务历史项
     * @param {string} taskId - 任务ID
     * @returns {Promise<Array>} - 更新后的任务历史
     */
    async deleteTaskHistoryItem(taskId) {
        try {
            // 获取当前任务历史
            const currentTaskHistory = await this.getTaskHistory();
            
            // 过滤掉要删除的任务
            const updatedTaskHistory = currentTaskHistory.filter(item => item.id !== taskId);
            
            // 保存到扩展全局状态
            await this.context.globalState.update(
                StorageConstants.STATE_KEYS.TASK_HISTORY,
                updatedTaskHistory
            );
            
            // 尝试删除任务目录
            try {
                const taskDir = path.join(this.globalStoragePath, StorageConstants.FOLDERS.TASKS, taskId);
                await fs.rm(taskDir, { recursive: true, force: true });
            } catch (deleteError) {
                console.error('删除任务目录失败:', deleteError);
                // 继续执行，不中断流程
            }
            
            return updatedTaskHistory;
        } catch (error) {
            console.error('删除任务历史项失败:', error);
            return await this.getTaskHistory();
        }
    }

    /**
     * 清除所有任务历史
     * @returns {Promise<void>}
     */
    async clearAllTaskHistory() {
        try {
            // 清除全局状态中的任务历史
            await this.context.globalState.update(StorageConstants.STATE_KEYS.TASK_HISTORY, []);
            
            // 删除所有任务目录
            try {
                const tasksDir = path.join(this.globalStoragePath, StorageConstants.FOLDERS.TASKS);
                await fs.rm(tasksDir, { recursive: true, force: true });
                // 重新创建空的任务目录
                await fs.mkdir(tasksDir, { recursive: true });
            } catch (deleteError) {
                console.error('删除任务目录失败:', deleteError);
                // 继续执行，不中断流程
            }
        } catch (error) {
            console.error('清除所有任务历史失败:', error);
        }
    }

    /**
     * 获取自定义指令
     * @returns {Promise<string>} - 自定义指令
     */
    async getCustomInstructions() {
        return this.context.globalState.get(StorageConstants.STATE_KEYS.CUSTOM_INSTRUCTIONS) || '';
    }

    /**
     * 保存自定义指令
     * @param {string} instructions - 自定义指令
     */
    async saveCustomInstructions(instructions) {
        await this.context.globalState.update(
            StorageConstants.STATE_KEYS.CUSTOM_INSTRUCTIONS,
            instructions
        );
    }

    /**
     * 获取聊天设置
     * @returns {Promise<Object>} - 聊天设置
     */
    async getChatSettings() {
        return this.context.globalState.get(StorageConstants.STATE_KEYS.CHAT_SETTINGS) || {
            modelId: 'qwen-turbo',
            temperature: 0.7,
            reasoningEffort: 'balanced'
        };
    }

    /**
     * 保存聊天设置
     * @param {Object} settings - 聊天设置
     */
    async saveChatSettings(settings) {
        await this.context.globalState.update(
            StorageConstants.STATE_KEYS.CHAT_SETTINGS,
            settings
        );
    }

    /**
     * 获取自动批准设置
     * @returns {Promise<Object>} - 自动批准设置
     */
    async getAutoApprovalSettings() {
        return this.context.globalState.get(StorageConstants.STATE_KEYS.AUTO_APPROVAL_SETTINGS) || {
            enableAutoApproval: false,
            autoApproveReadFile: false,
            autoApproveWriteToFile: false,
            autoApproveReplaceInFile: false,
            autoApproveExecuteCommand: false,
            maxConsecutiveAutoApprovedRequests: 3
        };
    }

    /**
     * 保存自动批准设置
     * @param {Object} settings - 自动批准设置
     */
    async saveAutoApprovalSettings(settings) {
        await this.context.globalState.update(
            StorageConstants.STATE_KEYS.AUTO_APPROVAL_SETTINGS,
            settings
        );
    }
}

module.exports = StorageManager; 